<template>
    <div class="set">
        <img src="../trade-list/img/back.png"
             @click="$router.replace('/upload')" />
        <!-- <div class="setContainer" id="img-container" @click="chose($event)"> -->
        <div class="setContainer"
             id="img-container">
            <img :src="imgUrl" />
            <div class="newADD"
                 v-if='isShow'
                 v-for="(item,idx) in coordInfos"
                 v-bind:key="idx"
                 :style="{left:item.x+'px',top: item.y+'px',width:item.w+'px',height:item.h+'px'}">
                <div class="left">{{idx+1}}</div>
            </div>
        </div>
        <input type="text"
               placeholder="请简要描述隐患情况（必填项）"
               v-model='info' />

        <p style="color: red;line-height: 3rem;font-size: 1.5rem;"
           v-if='flagTxt'>请填写隐患情况！</p>
        <p class="setBtn">
            <span @click='finshSet'>设置下一个隐患点</span>
            <span @click='getRight'>下一步</span>
        </p>
        <el-dialog title="提示"
                   width='80%'
                   :visible.sync="dialogVisible">
            <div class="tit">
                <i class="el-icon-warning"></i>
                <p> {{titContent}}</p>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    mapState,
    mapActions
} from 'vuex'
import errImgUrl from '@/components/trade-list/img/error.png'
import wx from 'weixin-js-sdk'
export default {
    name: "set",
    data () {
        return {
            flagTxt: false,
            imgUrl: localStorage.getItem('uploadImg'),
            coordInfos: [],
            coordInfos2: [{
                x: 0,
                y: 0,
                x2: 98,
                y2: 98,
                w: 98,
                h: 98,
                id: 1,
                according: '',
                resolve: '',
            }],
            titContent: '',
            dialogVisible: false,
            info: '',
            idx: 0,
            flag: true,
            isFinsh: true,
            isShow: false
        }
    },
    computed: {
        ...mapState({
            imgInfo: 'imgInfo',
            trade: 'trade'
        }),

    },
    methods: {
        setParam (one) {
            if (one) {
                this.coordInfos.push(one)
            }
            var varFileInfo = {
                'fileId': this.imgInfo.id,
                'fileName': this.imgInfo.name,
                'width': this.imgInfo.width,
                'height': this.imgInfo.height
            }
            var scaling = (this.imgInfo.width) / $('#img-container').width()
            var obj2 = []
            localStorage.setItem('coordInfos', JSON.stringify(this.coordInfos))
            this.coordInfos.map(function (item, index) {
                var item1 = {
                    x: Math.floor(item.x * scaling),
                    y: Math.floor(item.y * scaling),
                    x2: Math.floor(item.x2 * scaling),
                    y2: Math.floor(item.y2 * scaling),
                    w: Math.floor(item.w * scaling),
                    h: Math.floor(item.h * scaling),
                    according: '',
                    resolve: item.resolve,
                    id: index
                }
                obj2.push(item1)
            })
            var param = {
                'varFileInfo': JSON.stringify(varFileInfo),
                'varCoordInfo': JSON.stringify({
                    'coordInfos': obj2
                }),
                'createUserId': '',
                'varCreateUser': '',
                'datCreateDate': this.getCurrentTime(),
                'labelName': this.trade,
                'weChatName': '',
                'weChatUrl': ''
            }
            localStorage.uploadParam = JSON.stringify(param)
            this.goUpload()
        },
        getRight () {
            var that = this
            // this.idx++
            this.flag = false
            var targetObjLength = $('.targetObj0').length
            if (targetObjLength === 0 && this.coordInfos.length == 0) {
                this.titContent = '请设置隐患点 !'
                this.dialogVisible = true
            } else if (targetObjLength > 0 && this.coordInfos.length == 0) {
                if (this.info == '') {
                    this.flagTxt = true
                } else {
                    this.setCoordInfo('next')
                }
            } else {
                if (this.coordInfos.length > 0 && targetObjLength > 0) {
                    if (this.info == '') {
                        this.flagTxt = true
                    } else {
                        this.setCoordInfo('next')
                    }
                } else {
                    this.setParam()
                }
            }
        },
        setCoordInfo (next) {
            var left1 = Math.floor($('#targetObj').position().left)
            var top1 = Math.floor($('#targetObj').position().top)
            var addOne = {
                x: left1,
                y: top1,
                x2: left1 + 98,
                y2: top1 + 98,
                w: 98,
                h: 98,
                according: '',
                resolve: this.info,
                id: this.coordInfos.length
            }
            var flag = this.checkWrong(addOne.x, addOne.y)
            $('.targetObj0').remove()
            if (flag) {
                this.setParam(addOne)
                if (next) this.setParam()
            } else {
                this.titContent = '隐患区域不允许超出边界和重叠!'
                this.dialogVisible = true
                this.isFinsh = true
                this.chose()
            }
        },
        getCurrentTime () {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second)
        },
        goUpload () {
            let href = window.location.origin + window.location.pathname + window.location.hash
            var url1 = encodeURIComponent(href.split('#')[0] + '#/startUpload')
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf873bd7fdb2bd0be&redirect_uri=' + url1 + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
        },
        setDanger ($targetObj, idx) {
            $('.right').click(function () {
                $(this).parent().remove();
                that.isFinsh = true
                that.info = ''
                return false
            })
            var that = this
            var cat = window.cat || {};
            cat.touchjs = {
                left: 0,
                top: 0,
                scaleVal: 1, //缩放  
                rotateVal: 0, //旋转  
                curStatus: 0, //记录当前手势的状态, 0:拖动, 1:缩放, 2:旋转  
                //拖动  
                drag: function ($targetObj, callback) {
                    touch.on($targetObj, 'drag', function (ev) {
                        $targetObj.css("left", cat.touchjs.left + ev.x).css("top", cat.touchjs.top + ev.y);
                    });
                    touch.on($targetObj, 'dragend', function (ev) {
                        cat.touchjs.left = cat.touchjs.left + ev.x;
                        cat.touchjs.top = cat.touchjs.top + ev.y;
                        callback(cat.touchjs.left, cat.touchjs.top);
                    });
                },
                //缩放  
                scale: function ($targetObj, callback) {
                    var initialScale = cat.touchjs.scaleVal || 1;
                    var currentScale;
                    //                  touch.on($targetObj, 'pinch', function (ev) {
                    //                      if (cat.touchjs.curStatus == 2) {
                    //                          return;
                    //                      }
                    //                      cat.touchjs.curStatus = 1;
                    //                      currentScale = ev.scale - 1;
                    //                      currentScale = initialScale + currentScale;
                    //                      cat.touchjs.scaleVal = currentScale;
                    //                      var transformStyle = 'scale(' + cat.touchjs.scaleVal + ') rotate(' + cat.touchjs.rotateVal + 'deg)';
                    //                      $targetObj.css("transform", transformStyle).css("-webkit-transform", transformStyle);
                    //                      callback(cat.touchjs.scaleVal);
                    //                  });
                    //                  touch.on($targetObj, 'pinchend', function (ev) {
                    //                      if (cat.touchjs.curStatus == 2) {
                    //                          return;
                    //                      }
                    //                      initialScale = currentScale;
                    //                      cat.touchjs.scaleVal = currentScale;
                    //                      callback(cat.touchjs.scaleVal);
                    //                  });
                },
            };
            //初始化拖动手势（不需要就注释掉）  
            cat.touchjs.drag($targetObj, function (left, top) {

                var obj = {}
                left = Math.floor(left)
                top = Math.floor(top)
                var boxHeight = Math.floor($('#img-container').height())
                var boxWidth = Math.floor($('#img-container').width())
                var objWidth = Math.floor($targetObj.width())
                var objHeight = Math.floor($targetObj.height())
                var maxHeight = boxHeight - objHeight
                var maxWidth = boxWidth - objWidth
                var flag = that.checkWrong(left, top)
                if ((left < 0) || (left > maxWidth) || (top < 0) || (top > maxHeight) || (!flag)) {
                    that.titContent = '隐患区域不允许超出边界和重叠!'
                    that.dialogVisible = true
                    $targetObj.remove()
                    that.flagTxt = false
                    that.isFinsh = true
                    that.chose()
                } else {
                    obj.x = left
                    obj.y = top
                    obj.x2 = obj.x + objWidth
                    obj.y2 = obj.y + objHeight
                    obj.w = objWidth
                    obj.h = objHeight
                    obj.according = ''
                    obj.resolve = $('input').val()
                    obj.id = that.coordInfos.length
                    that.coordInfos2.push(obj)
                }
            });
            //初始化缩放手势（不需要就注释掉）  
            //          cat.touchjs.scale($targetObj, function (scale) { });
        },
        checkWrong (x, y) {
            var flag = true
            this.coordInfos.map(function (item) {
                var x0 = Math.abs(item.x - x)
                var y0 = Math.abs(item.y - y)
                if ((x0 <= item.w) && (y0 <= item.h)) {
                    flag = false
                }
            })
            return flag
        },
        finshSet () {
            this.isShow = true
            var left = $('.targetObj0').css('left')
            var top = $('.targetObj0').css('top')
            if ((this.coordInfos2.length != 0) && (this.info != '') && ($('.targetObj0').length != 0)) {
                this.isFinsh = true
                var index = this.coordInfos2.length == 0 ? 0 : (this.coordInfos2.length - 1)
                var obj = this.coordInfos2[index]
                var obj0 = {
                    x: 0,
                    y: 0,
                    x2: 98,
                    y2: 98,
                    w: 98,
                    h: 98,
                    id: 1,
                    according: '',
                    resolve: this.info,
                }
                obj.resolve = this.info
                if ((left == '0px') && (top == '0px')) {
                    var flag = this.checkWrong(0, 0)
                    if (flag) {
                        this.coordInfos.push(obj0)
                    } else {
                        this.titContent = '隐患区域不允许超出边界和重叠!'
                        this.dialogVisible = true
                    }
                } else {
                    var flag = this.checkWrong(obj.x, obj.y)
                    if (flag) {
                        this.coordInfos.push(obj)
                    }
                }
                this.info = ''
                this.flagTxt = false
                $('.targetObj' + this.idx).remove()

            }
            else {
                if (this.info) {
                    this.titContent = '请设置隐患区域 !'
                    this.dialogVisible = true
                    this.flagTxt = false
                } else {
                    this.flagTxt = true
                }
            }
            this.chose()
        },
        chose () {
            var idx2 = this.coordInfos.length + 1
            var str = '<div id="targetObj" class="targetObj' + this.idx + '">' +
                '<div class="left">' + idx2 + '</div>' +
                '<div class="right">x</div>' +
                '</div>'

            if (this.isFinsh) {
                $('.setContainer').append(str)
                this.setDanger($('.targetObj' + this.idx))
                $('.targetObj' + this.idx).css({
                    'left': 0,
                    'top': 0,
                    'zIndex': 1
                })
                this.isFinsh = false
            }
        }
    },
    mounted () {
        this.chose()
    }
}
</script>

<style lang="less">
.set {
    height: 100%;
    width: 100%;
    padding: 0 4%;
    .tit {
        height: 6rem;
        display: flex;
        align-items: center;
        p {
            font-size: 16px;
            font-weight: 800;
        }
        i {
            color: red;
            font-size: 30px;
            padding: 0 2rem 0 3rem;
        }
    }
    .newADD {
        position: absolute;
        border: 1px solid #000000;
        .left {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #fff;
            padding: 0;
            text-align: center;
            line-height: 20px;
            float: left;
            border: 1px solid #000000;
            margin: -10px;
        }
    }
    .setContainer {
        display: inline-block;
        position: relative;
        border: 1px solid #ccc;
        width: 100%;
        padding-bottom: -100px;
        img {
            display: block;
            width: 100%;
        }
        #targetObj {
            width: 100px;
            height: 100px;
            position: absolute;
            transform-origin: center;
            border: 1px solid #000000;
            .left {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #fff;
                padding: 0;
                text-align: center;
                line-height: 20px;
                float: left;
                border: 1px solid #000000;
                margin: -10px;
            }
            .right {
                width: 20px;
                height: 20px;
                text-align: center;
                line-height: 20px;
                font-size: 30px;
                color: red;
                float: right;
                margin: -10px;
            }
        }
    }
    .title {
        display: flex;
        padding: 0 20px;
        justify-content: space-between;
        border-bottom: 1px solid #ccc;
        span {
            line-height: 40px;
            font-size: 16px;
            display: flex;
            align-items: center;
            i {
                font-style: normal;
                font-size: 30px;
            }
        }
    }
    input {
        width: 100%;
        height: 5rem;
        text-indent: 1rem;
        margin-top: 1rem;
        border-radius: 0.5rem;
        color: #000000;
        font-size: 1.5rem;
        border: 1px solid #ccc;
    }
    .setBtn {
        margin: 1rem 0;
        display: flex;
        justify-content: space-between;
        border-bottom: 0;
        span {
            display: inline-block;
            background: #6495ed;
            line-height: 3rem;
            width: 13.5rem;
            font-size: 1.3rem;
            color: #fff;
            text-align: center;
            border-radius: 1.5rem;
        }
    }
}
</style>